# -*- encoding: utf-8 -*-
import datetime
from flask import Flask, request
from flask_session import Session
from flask import g
from flask_login import current_user, LoginManager
from flask_sqlalchemy import SQLAlchemy
from .config import Config
# here put the import lib

app = Flask(__name__)

app.config.from_object(Config)
db = SQLAlchemy(app)
db.metadata.clear()


app.config['SESSION_TYPE'] = 'sqlalchemy'  # session类型为sqlalchemy
app.config['SESSION_SQLALCHEMY'] = db  # SQLAlchemy对象
app.config['SESSION_SQLALCHEMY_TABLE'] = 'sys_session'  # session要保存的表名称
app.config['SESSION_PERMANENT'] = True  # 如果设置为True，则关闭浏览器session就失效。
app.config['SESSION_USE_SIGNER'] = False  # 是否对发送到浏览器上session的cookie值进行加密
app.config['SESSION_KEY_PREFIX'] = 'session:'  # 保存到session中的值的前缀
app.config['PERMANENT_SESSION_LIFETIME'] = datetime.timedelta(hours=1)
Session(app)

# CSRFProtect(app)

login_manager = LoginManager()
login_manager.login_view = 'views.login'
login_manager.login_message_category = 'info'
login_manager.login_message = '请登录！'
login_manager.init_app(app)


@app.before_request
def before_request():
    g.user = current_user


from .models.UserMinModel import UserMin
@login_manager.user_loader
def loader_user(user_id):
    result_dict = UserMin.get(user_id)
    if result_dict.get("code") == '200':
        return result_dict.get("data")
    return None


# 创建全站拦截器，每个请求之后根据请求方法统一设置返回头
@app.after_request
def process_response(response):
    allow_cors = ['OPTIONS', 'PUT', 'DELETE', 'GET', 'POST']
    if request.method in allow_cors:
        response.headers["Access-Control-Allow-Origin"] = '*'
        response.headers['Access-Control-Allow-Methods'] = 'OPTIONS,GET,POST,PUT,DELETE'
        response.headers['Access-Control-Allow-Headers'] = 'content-type,x-ijt'
    return response


# 接口注册
from .utils.commons import ReConverter
app.url_map.converters["re"] = ReConverter

from .api import main_api
app.register_blueprint(main_api, url_prefix="/api")

from .views import view
app.register_blueprint(view, url_prefix="")